package com.chenjiahao.kaiyanwan.ui.home

import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityOptionsCompat
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import com.chenjiahao.kaiyanwan.R
import com.chenjiahao.kaiyanwan.base.BaseFragment
import com.chenjiahao.kaiyanwan.logic.exception.ErrorStatus
import com.chenjiahao.kaiyanwan.logic.exception.ExceptionHandle
import com.chenjiahao.kaiyanwan.logic.exception.ExceptionHandle.Companion.handleException
import com.chenjiahao.kaiyanwan.logic.util.StatusBarUtil
import com.chenjiahao.kaiyanwan.showToast
import com.chenjiahao.kaiyanwan.ui.search.SearchActivity
import com.hazz.kotlinmvp.mvp.model.bean.HomeBean
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_home.*
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*

class HomeFragment : BaseFragment() {

    private var mTitle: String? = null
    private var num = 1
    private var isRefresh = false
    private var loadingMore = false
    private lateinit var mHomeAdapter: HomeAdapter
    var nextPageUrl: String? = null
    private var mMaterialHeader: ClassicsHeader? = null

    private val simpleDateFormat by lazy {
        SimpleDateFormat("- MMM. dd, 'Brunch' -", Locale.ENGLISH)
    }


    val viewModel by lazy { ViewModelProvider(this).get(HomeViewModel::class.java) }


    override fun getLayoutId(): Int = R.layout.fragment_home

    companion object {
        fun getInstance(title: String): HomeFragment {
            val fragment = HomeFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.mTitle = title
            return fragment
        }
    }

    private val linearLayoutManager by lazy {
        LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    }

    override fun initView() {
        mRefreshLayout.setEnableHeaderTranslationContent(true)
        mRefreshLayout.setOnRefreshListener {
            isRefresh = true
            viewModel.getHomeData(num)
        }
        iv_search.setOnClickListener { openSearchActivity() }
        mMaterialHeader = mRefreshLayout.refreshHeader as ClassicsHeader?
        //设置下拉刷新主题颜色
        mRefreshLayout.setPrimaryColorsId(R.color.color_light_black, R.color.color_title_bg)
        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == SCROLL_STATE_IDLE) {
                    val childCount = mRecyclerView.childCount //可见的item个数有多少个
                    val itemCount = (mRecyclerView.layoutManager as LinearLayoutManager).itemCount
                    val firstVisibleItem =
                        (mRecyclerView.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                    if (firstVisibleItem + childCount == itemCount) {
                        if (!loadingMore) {
                            loadingMore = true
                            nextPageUrl?.let { viewModel.getMoreData(it) }
                        }
                    }
                }

            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val currentVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition()
                if (currentVisibleItemPosition == 0) {
                    //背景设置为透明
                    toolbar.setBackgroundColor(getColor(R.color.color_translucent))
                    iv_search.setImageResource(R.mipmap.ic_action_search_white)
                    tv_header_title.text = ""
                } else {
                    if (mHomeAdapter?.mData!!.size > 1) {
                        toolbar.setBackgroundColor(getColor(R.color.color_title_bg))
                        iv_search.setImageResource(R.mipmap.ic_action_search_black)
                        val itemList = mHomeAdapter!!.mData
                        val item =
                            itemList[currentVisibleItemPosition + mHomeAdapter!!.bannerItemSize - 1]
                        if (item.type == "textHeader") {
                            tv_header_title.text = item.data?.text
                        } else {
                            tv_header_title.text = simpleDateFormat.format(item.data?.date)
                        }
                    }

                }
            }
        })

        mLayoutStatusView = multipleStatusView
        //状态栏透明和间距处理
        activity?.let { StatusBarUtil.darkMode(it) }
        activity?.let { StatusBarUtil.setPaddingSmart(it, toolbar) }

    }


    override fun lazyLoad() {
        showLoading()
        viewModel.getHomeData(num)
        viewModel.homeLiveData.observe(this, Observer {
            val homeData = it.getOrNull()
            if (homeData != null) {
                val homeBean: HomeBean = homeData
                this.nextPageUrl = homeBean.nextPageUrl
                nextPageUrl?.let { viewModel.getMoreData(it) }
                val bannerItemList = homeBean.issueList[0].itemList
                bannerItemList.filter { it.type == "banner2" || it.type == "horizontalScrollCard" }
                    .forEach {
                        bannerItemList.remove(it)
                    }
                // 重新赋值 Banner 长度
                homeBean!!.issueList[0].count = homeBean!!.issueList[0].itemList.size
                viewModel.itemList.clear()
                viewModel.itemList.addAll(homeBean?.issueList!![0].itemList)
                mHomeAdapter?.setBannerSize(homeBean.issueList[0].count)
            } else {
                dismissLoading()
                it.exceptionOrNull()?.printStackTrace()
                showError(handleException(it.exceptionOrNull() as Exception), ExceptionHandle.errorCode)
            }
        })

        viewModel.homeMoreLiveData.observe(this, Observer {
            loadingMore = false
            mLayoutStatusView?.showContent()
            dismissLoading()
            val moreData = it.getOrNull()
            if (moreData != null) {
                val moreHomeData = moreData as HomeBean
                val newItemList = moreHomeData.issueList[0].itemList
                newItemList.filter { item ->
                    item.type == "banner2" || item.type == "horizontalScrollCard"
                }.forEach { item ->
                    //移除 item
                    newItemList.remove(item)
                }
                nextPageUrl = moreHomeData.nextPageUrl
                mHomeAdapter?.addItemData(newItemList)
            } else {
                showToast("" + it.exceptionOrNull()?.printStackTrace())
                showError(handleException(it.exceptionOrNull() as Exception), ExceptionHandle.errorCode)
                it.exceptionOrNull()?.printStackTrace()
            }
        })
        // Adapter
        mHomeAdapter = HomeAdapter(activity as FragmentActivity, viewModel.itemList)
        mRecyclerView.adapter = mHomeAdapter
        mRecyclerView.layoutManager = linearLayoutManager
        mRecyclerView.itemAnimator = DefaultItemAnimator()
    }


    private fun showLoading() {
        if (!isRefresh) {
            isRefresh = false
            mLayoutStatusView?.showLoading()
        }
    }

    /**
     * 隐藏 Loading
     */
    fun dismissLoading() {
        mRefreshLayout.finishRefresh()
    }

    private fun showEmptyDataView() {
        mLayoutStatusView?.showEmpty()
    }


    fun getColor(colorId: Int): Int {
        return resources.getColor(colorId)
    }

    private fun openSearchActivity() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val options = activity?.let {
                ActivityOptionsCompat.makeSceneTransitionAnimation(
                    it,
                    iv_search,
                    iv_search.transitionName
                )
            }
            startActivity(Intent(activity, SearchActivity::class.java), options?.toBundle())
        } else {
            startActivity(Intent(activity, SearchActivity::class.java))
        }
    }


}